package com.atguigu.spzx.pay.controller;

import com.alipay.api.internal.util.AlipaySignature;
import com.atguigu.spzx.model.vo.common.Result;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.pay.properties.AlipayProperties;
import com.atguigu.spzx.pay.service.AlipayService;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Tag(name = "支付接口")
@RestController
@RequestMapping("api/order/alipay")
public class AlipayController {

    @Autowired
    AlipayService alipayService;

    @Autowired
    AlipayProperties properties;


    @Tag(name = "取消订单接口修改订单状态")
    @GetMapping("cancelPayment/{orderNo}")
    public Result cancelPayment(@PathVariable String orderNo){
        alipayService.cancelPayment(orderNo);
        return Result.build(null, ResultCodeEnum.SUCCESS);

    }


    @Tag(name = "向支付宝返回form表单")
    @GetMapping("submitAlipay/{orderNo}")
    public Result submitAlipay(@PathVariable String orderNo){
        String form = alipayService.alipay(orderNo);
        return Result.build(form, ResultCodeEnum.SUCCESS);

    }

    @Tag(name = "回调接口")
    @PostMapping("/callback/notify")
    public String callback( @RequestParam Map<String, String> paramsMap){
        //1、签名校验
        try {
            boolean signVerified = AlipaySignature.rsaCheckV1(paramsMap,properties.getAlipay_public_key() , AlipayProperties.charset , AlipayProperties.sign_type); //调用SDK验证签名
//            boolean signVerified = true;
            if(signVerified){

                //判断是否支付成功
                String trade_status = paramsMap.get("trade_status");
                if(trade_status.equals("TRADE_SUCCESS")){
                    //支付成功！！！
                    //1、修改订单  2、修改支付记录  3、修改商品库存和销量
                    alipayService.afterPaySuccess(paramsMap);

                }
                //验签成功
                return "success";
            }else{
                //验签失败
                return "failure";
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
